package com.mlan.userap.activity;

import android.Manifest;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.Preview;
import androidx.camera.core.TorchState;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.video.MediaStoreOutputOptions;
import androidx.camera.video.Recorder;
import androidx.camera.video.Recording;
import androidx.camera.video.VideoCapture;
import androidx.camera.video.VideoRecordEvent;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.common.util.concurrent.ListenableFuture;
import com.mlan.userap.R;
import com.mlan.userap.untils.LogHelper;

import java.io.File;
import java.util.concurrent.ExecutionException;

public class CameraActivity extends AppCompatActivity {
    private static final int CAMERA_PERMISSION_REQUEST_CODE = 100;
    private PreviewView previewView;
    private Button captureButton, flipButton, flashButton;
    ;
    private ImageCapture imageCapture;
    private boolean isRecording = false; // 假设使用 MediaRecorder 录视频，此处仅模拟

    private boolean isLongPressDetected = false; // 新增标志位

    private CameraSelector cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;

    private VideoCapture<Recorder> videoCapture; // 使用新版 VideoCapture

    private Recording recording;
    private ProcessCameraProvider cameraProvider;
    private Camera camera;
    private Runnable longPressRunnable;

    private Handler handler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogHelper.i("CameraActivity onCreate 被调用");
        setContentView(R.layout.activity_camera);

        previewView = findViewById(R.id.previewView);
        captureButton = findViewById(R.id.captureButton);

        flipButton = findViewById(R.id.flipButton);
        flashButton = findViewById(R.id.flashButton);
        flipButton.setOnClickListener(v -> flipCamera());
        flashButton.setOnClickListener(v -> toggleFlash());
        // 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}, CAMERA_PERMISSION_REQUEST_CODE);
        } else {
            startCamera();
        }

        longPressRunnable = () -> {
            if (!isRecording) {
                isLongPressDetected = true;
                LogHelper.i("拍视频了");
                isRecording = true;
                startRecording();
                captureButton.setText("录制中...");
            } else {
                LogHelper.i("长按，其它");
            }
        };

        // 设置触摸事件
        captureButton.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    isLongPressDetected = false; // 重置标志位
                    handler.postDelayed(longPressRunnable, 500);
                    return true;
                case MotionEvent.ACTION_UP:
                    if (!isLongPressDetected) {
                        takePhoto(); // 短按拍照
                    } else if (isRecording) {
                        stopRecording(); // 松手停止录制
                        isRecording = false;
                        captureButton.setText("拍照/录视频");
                    }
                    handler.removeCallbacks(longPressRunnable);
                    return true;
                case MotionEvent.ACTION_CANCEL:
                    handler.removeCallbacks(longPressRunnable);
                    return true;
            }
            return false;
        });
    }

    private void startCamera() {
        LogHelper.i("开始启动相机");
        // 确保先清理之前的资源
        if (cameraProvider != null) {
            try {
                cameraProvider.unbindAll();
                LogHelper.i("清理之前的相机资源");
            } catch (Exception e) {
                LogHelper.i("清理相机资源时出错: " + e.getMessage());
            }
        }
        
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);
        cameraProviderFuture.addListener(() -> {
            try {
                cameraProvider = cameraProviderFuture.get();
                bindCameraUseCases();
                LogHelper.i("相机启动成功");
            } catch (ExecutionException | InterruptedException e) {
                LogHelper.i("相机启动失败: " + e.getMessage());
                Toast.makeText(this, "相机启动失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }, ContextCompat.getMainExecutor(this));
    }

    private void bindCameraUseCases() {
        LogHelper.i("开始绑定相机用例");
        try {
            // 先解绑所有用例
            if (cameraProvider != null) {
                cameraProvider.unbindAll();
                LogHelper.i("解绑所有现有相机用例");
            }

            Preview preview = new Preview.Builder().build();
            preview.setSurfaceProvider(previewView.getSurfaceProvider());

            imageCapture = new ImageCapture.Builder()
                    .setFlashMode(ImageCapture.FLASH_MODE_AUTO)
                    .build();

            videoCapture = VideoCapture.withOutput(new Recorder.Builder().build());

            camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture, videoCapture);
            LogHelper.i("相机用例绑定成功");
        } catch (Exception e) {
            LogHelper.i("绑定相机用例时出错: " + e.getMessage());
            Toast.makeText(this, "相机初始化失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void flipCamera() {
        cameraSelector = (cameraSelector == CameraSelector.DEFAULT_BACK_CAMERA)
                ? CameraSelector.DEFAULT_FRONT_CAMERA
                : CameraSelector.DEFAULT_BACK_CAMERA;
        bindCameraUseCases();
    }

    private void toggleFlash() {
        if (camera != null && camera.getCameraInfo().hasFlashUnit()) {
            boolean isTorchOn = camera.getCameraInfo().getTorchState().getValue() == TorchState.ON;
            camera.getCameraControl().enableTorch(!isTorchOn);
            flashButton.setText(isTorchOn ? "开启闪光" : "关闭闪光");
        } else {
            Toast.makeText(this, "设备不支持闪光灯", Toast.LENGTH_SHORT).show();
        }
    }


    private void takePhoto() {
        // File photoFile = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "photo_" + System.currentTimeMillis() + ".jpg");
        // ImageCapture.OutputFileOptions outputOptions = new ImageCapture.OutputFileOptions.Builder(photoFile).build();
//        imageCapture.takePicture(outputOptions, ContextCompat.getMainExecutor(this), new ImageCapture.OnImageSavedCallback() {
//            @Override
//            public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
//                Toast.makeText(CameraActivity.this, "照片保存至: " + photoFile.getAbsolutePath(), Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onError(@NonNull ImageCaptureException exception) {
//                Toast.makeText(CameraActivity.this, "拍照失败: " + exception.getMessage(), Toast.LENGTH_SHORT).show();
//            }
//        });

        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, "photo_" + System.currentTimeMillis() + ".jpg");
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);

        ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions.Builder(
                getContentResolver(),
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                contentValues
        ).build();
        imageCapture.takePicture(outputFileOptions, ContextCompat.getMainExecutor(this), new ImageCapture.OnImageSavedCallback() {
            @Override
            public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                Toast.makeText(CameraActivity.this, "照片保存至: " + outputFileResults.getSavedUri().getPath(), Toast.LENGTH_SHORT).show();
                MediaScannerConnection.scanFile(CameraActivity.this,
                        new String[]{outputFileResults.getSavedUri().getPath()}, new String[]{"image/jpeg"}, null);
            }

            @Override
            public void onError(@NonNull ImageCaptureException exception) {
                Toast.makeText(CameraActivity.this, "拍照失败: " + exception.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void startRecording() {
        // 这里仅模拟录视频逻辑，实际需使用 MediaRecorder 或 CameraX 的 VideoCapture
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Video.Media.DISPLAY_NAME, "video_" + System.currentTimeMillis() + ".mp4");
        contentValues.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
        contentValues.put(MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_MOVIES);

        MediaStoreOutputOptions options = new MediaStoreOutputOptions.Builder(
                getContentResolver(),
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI
        ).setContentValues(contentValues).build();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        recording = videoCapture.getOutput()
                .prepareRecording(this, options)
                .withAudioEnabled()
                .start(ContextCompat.getMainExecutor(this), videoRecordEvent -> {
                    if (videoRecordEvent instanceof VideoRecordEvent.Start) {
                        Toast.makeText(this, "开始录视频", Toast.LENGTH_SHORT).show();
                    } else if (videoRecordEvent instanceof VideoRecordEvent.Finalize) {
                        VideoRecordEvent.Finalize finalizeEvent = (VideoRecordEvent.Finalize) videoRecordEvent;
                        if (finalizeEvent.hasError()) {
                            Toast.makeText(this, "录视频失败: " + finalizeEvent.getError(), Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(this, "视频已保存到相册", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void stopRecording() {
        if (recording != null) {
            recording.stop();
            recording = null;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogHelper.i("CameraActivity onDestroy 被调用");
        if (recording != null) {
            recording.stop();
            recording = null;
            LogHelper.i("停止录制并释放recording资源");
        }
        if (cameraProvider != null) {
            try {
                cameraProvider.unbindAll();
                LogHelper.i("解绑所有相机用例");
            } catch (Exception e) {
                LogHelper.i("解绑相机用例时出错: " + e.getMessage());
            }
        }
        if (imageCapture != null) {
            imageCapture = null;
            LogHelper.i("释放imageCapture资源");
        }
        if (videoCapture != null) {
            videoCapture = null;
            LogHelper.i("释放videoCapture资源");
        }
        if (camera != null) {
            camera = null;
            LogHelper.i("释放camera资源");
        }
        handler.removeCallbacksAndMessages(null);
        LogHelper.i("移除所有handler消息");
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startCamera();
        } else {
            Toast.makeText(this, "需要相机权限", Toast.LENGTH_SHORT).show();
        }
    }


}